package org.awenlice.playerdailyshop.gui;

import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.ChestMenu;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.network.chat.Component;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.awenlice.playerdailyshop.coin.PlayerCoinSystem;
import org.awenlice.playerdailyshop.data.PlayerBuyShopData;
import org.awenlice.playerdailyshop.data.PlayerBuyShopDataManager;

public class BuyShopMenu extends ChestMenu {
    private static final Logger LOGGER = LogManager.getLogger();

    public BuyShopMenu(int windowId, net.minecraft.world.entity.player.Inventory playerInventory, net.minecraft.world.Container buyShopInventory) {
        super(MenuType.GENERIC_9x3, windowId, playerInventory, buyShopInventory, 3); // 3 表示 3 行
    }

    @Override
    public ItemStack quickMoveStack(Player player, int slotIndex) {
        return ItemStack.EMPTY; // 禁止拿取物品
    }

    @Override
    public void clicked(int slotIndex, int button, net.minecraft.world.inventory.ClickType clickType, Player player) {
        // 拦截双击操作
        if (clickType == ClickType.PICKUP_ALL) { return;}

        if (slotIndex >= 0 && slotIndex < this.slots.size()) {
            Slot slot = this.slots.get(slotIndex);
            ItemStack stack = slot.getItem();

            // 检查是否是从收购商店容器中点击物品
            if (slot.container != player.getInventory() && !stack.isEmpty()) {
                int price = stack.getOrCreateTag().getInt("price");

                // 检查玩家背包中是否有匹配的物品（包括 NBT 属性）
                ItemStack playerStack = findMatchingItemInPlayerInventory(player, stack);
                if (!playerStack.isEmpty()) {
                    // 扣除玩家背包中的物品
                    playerStack.shrink(1);
                    // 给予玩家金币
                    PlayerCoinSystem.addCoins(player, price);
                    // 删除商店内的该物品
                    slot.set(ItemStack.EMPTY);
                    // 更新 PlayerShopData 中的数据
                    if (player instanceof ServerPlayer) {
                        ServerPlayer serverPlayer = (ServerPlayer) player;
                        PlayerBuyShopData shopData = PlayerBuyShopDataManager.get(serverPlayer);
                        shopData.getBuyShopItems().set(slotIndex, ItemStack.EMPTY); // 更新出售商店数据
                        shopData.setDirty(); // 标记数据为脏，需要保存
                    }
                } else {
                    player.displayClientMessage(Component.translatable("pds.notHasItem"), false);
                }
                return; // 拦截操作
            }
        }

        // 其他情况（如玩家背包内的操作）正常处理
        super.clicked(slotIndex, button, clickType, player);
    }

    /**
     * 在玩家背包中查找匹配的物品（忽略商店物品的额外 NBT 数据）
     */
    private ItemStack findMatchingItemInPlayerInventory(Player player, ItemStack targetStack) {
        // 创建一个副本，移除商店物品的额外 NBT 数据
        ItemStack strippedTargetStack = targetStack.copy();
        strippedTargetStack.removeTagKey("price");
        strippedTargetStack.removeTagKey("weight");

        for (ItemStack stack : player.getInventory().items) {
            if (ItemStack.isSameItemSameTags(stack, strippedTargetStack)) {
                return stack;
            }
        }
        return ItemStack.EMPTY;
    }
}